package com.lmabbe.common.datasources.core;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lmabbe.common.global.context.LmabbeSessionUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Objects;

/**
 * @author lmabbe
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_TIME = "createTime";
    public static final String CREATE_BY = "createBy";
    public static final String MODIFY_TIME = "modifyTime";
    public static final String MODIFY_BY = "modifyBy";

    private LmabbeSessionUser lmabbeSessionUser;


    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValues(metaObject, CREATE_BY, null == lmabbeSessionUser ? "system" : lmabbeSessionUser.getUserId());
        setFieldValues(metaObject, CREATE_TIME, DateUtil.date().toJdkDate());
        setFieldValByName(MODIFY_BY, null == lmabbeSessionUser ? "system" : lmabbeSessionUser.getUserId(), metaObject);
        setFieldValByName(MODIFY_TIME, DateUtil.date().toJdkDate(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(MODIFY_BY, null == lmabbeSessionUser ? "system" : lmabbeSessionUser.getUserId(), metaObject);
        setFieldValByName(MODIFY_TIME, DateUtil.date().toJdkDate(), metaObject);
    }

    /**
     * 设置字段值
     * 如果字段有值则不赋值
     *
     * @param metaObject 赋值的对象
     * @param fieldName  赋值的字段
     * @param value      值
     * @date 2021/12/6 2:48 下午
     * @author liming
     */
    private void setFieldValues(MetaObject metaObject, String fieldName, Object value) {
        if (metaObject.hasSetter(fieldName) && Objects.isNull(metaObject.getValue(fieldName))) {
            setFieldValByName(fieldName, value, metaObject);
        }
    }
}